package com.qidian.zl.paper.servlets;

import com.qidian.zl.paper.factory.ServiceFactory;
import com.qidian.zl.paper.service.AnswerService;
import com.qidian.zl.paper.util.JsonTools;
import com.qidian.zl.paper.util.StResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = {"/answer/delete","/answer/queryAnswerByTime"})
public class AnswerServlet extends HttpServlet {
    private AnswerService answerService= ServiceFactory.getAnswerService();
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uri = request.getRequestURI();
        if (uri.endsWith("delete")){
            delete(request,response);
        }else if(uri.endsWith("queryAnswerByTime")){
            queryAnswerByTime(request,response);
        }
    }

    private void queryAnswerByTime(HttpServletRequest request, HttpServletResponse response) throws IOException {
        StResult result = null;
        int page =1;
        int size = 10;
        try{page = Integer.parseInt(request.getParameter("page"));}catch (Exception e){}
        try{size = Integer.parseInt(request.getParameter("size"));}catch (Exception e){}

        try {
            Long paperId = Long.parseLong(request.getParameter("paperId"));
            String startTime = request.getParameter("startTime");
            String endTime = request.getParameter("endTime");
            //查询
            result= answerService.queryAnswerByTime(paperId,startTime,endTime,page,size);

        } catch (NumberFormatException e) {
            e.printStackTrace();
            result = StResult.fail("请传入正确的问卷编号");
        }
        // 输出result对象
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JsonTools.obj2String(result));
    }

    private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        StResult stResult=null;
        String groupId = request.getParameter("groupId");

        if(answerService.delete(groupId)>0){
            stResult=StResult.ok("删除成功");
        }else {
            stResult=StResult.fail("删除失败");
        }
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JsonTools.obj2String(stResult));
    }





}
